<template>
  <div>
    <div class="header">
      <span style="margin-left: 20px">关键字</span>
      <el-input placeholder="请输入关键字" v-model="caseReq.keyword" style="width: 140px; margin-left: 10px"
        clearable></el-input>
      <span style="text-align: right; margin-left: 10px">出险日期</span>
      <el-date-picker v-model="caseReq.accidentDates" type="daterange" align="right" unlink-panels range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions" style="margin-left: 10px; width: 240px"></el-date-picker>
      <span style="text-align: right; margin-left: 10px">提交日期</span>
      <el-date-picker v-model="caseReq.createDates" type="daterange" align="right" unlink-panels range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions" style="margin-left: 10px; width: 240px"></el-date-picker>
      <span style="text-align: right; margin-left: 10px">主办人员</span>
      <el-select filterable v-model="caseReq.hosterId" clearable style="margin-left: 10px;width: 200px">
        <el-option v-for="(item, index) in hosters" :key="index" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 20px" size="small" @click="
        caseReq.pageIndex = 1
      getDatas()
        ">
        搜索
      </el-button>
      <el-button type="warning" style="margin-left: 10px" size="small" @click="outputUnBillExcel">
        导出报表
      </el-button>
    </div>
    <div class="main">
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="概览" name="stat">
          <div ref="chart1" style="margin-top:50px;width: 100%; height: 60vh"></div>
        </el-tab-pane>
        <el-tab-pane label="图表" name="table">
          <el-table style="overflow: auto" height="640px" :data="caseRes.Items" stripe border highlight-current-row>
            <el-table-column type="index" width="40"></el-table-column>
            <el-table-column label="案件信息" width="500">
              <template slot-scope="scope">
                <div>{{ scope.row.FLOW_Name }}</div>
                <div>
                  案件状态：{{ scope.row.CS_StatusDesc }}{{ ' ' }}
                  {{ scope.row.CS_AllowLog ? '允许添加日志' : '不允许添加日志'
                  }}{{ ' ' }}
                  {{
                    scope.row.CS_AllowExpense
                      ? '允许差旅报销'
                      : '不允许差旅报销'
                  }}
                </div>
                <div>差旅性质：{{ scope.row.EXTY_EnumTxt }}</div>
                <div>
                  [ID]流水号：[{{ scope.row.CS_ID }}]{{ scope.row.CS_No }}
                </div>
                <div v-if="scope.row.CS_InsureCmpCaseNo">
                  报案号：{{ scope.row.CS_InsureCmpCaseNo }}
                </div>
                <div v-if="scope.row.CS_AppraiserCmpCaseNo">
                  案件编号：{{ scope.row.CS_AppraiserCmpCaseNo }}
                </div>
                <div>案件名称：{{ scope.row.CS_DisplayName }}</div>
                <div>
                  出险日期：{{ scope.row.CS_AccidentTime | formatDate }}
                </div>
                <div>提交时间：{{ scope.row.CS_CreateTime | formatDate }}</div>
                <div v-if="scope.row.CS_EndCaseDate">
                  结案日期：{{ scope.row.CS_EndCaseDate | formatDate }}
                </div>
                <div v-if="scope.row.CS_AccidentAreaDesc">
                  案发地区：{{ scope.row.CS_AccidentAreaDesc }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="公司/人员信息" width="500">
              <template slot-scope="scope">
                <div v-for="item in scope.row.Employees" :key="item.CSEP_ID">
                  {{ item.CSEP_TypeDesc }}：{{
                    item.CCV_TargetID == curEmp.CCV_TargetID
                      ? ''
                      : item.CMP_Name
                  }}{{ item.USR_Name ? '[' + item.USR_Name + ']' : '' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="开票信息" width="360">
              <template slot-scope="scope">
                <div style="font-size: 18px;">收费项目：{{ scope.row.ChargeSum }}元 </div>
                <div v-for="item in scope.row.Charges" :key="item.CSCG_ID">
                  【{{ item.CHTY_EnumTxt }}】{{ item.CSCG_Fee }}元
                </div>
                <div style="margin-top: 20px;font-size: 18px;">已开票：{{ scope.row.BillSum }}元 </div>
                <div v-for="item in scope.row.Bills" :key="item.CSCG_ID">
                  <span>【{{ item.BuyCompanyShortName ? item.BuyCompanyShortName : item.BuyCompanyName }}】</span>{{
                    item.CSB_Fee }}元
                </div>
                <div style="margin-top: 20px;font-size: 18px;"> 未开票：{{ scope.row.UnBillSum }}元</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button type="text" size="small" @click="toForm(scope.row.CS_FormID)" icon="el-icon-search">
                    登记流程
                  </el-button>
                  <el-button type="text" size="small" @click="toCaseInfoPage(scope.row.CS_ID)" icon="el-icon-coin">
                    案件详情
                  </el-button>
                </div>
                <div>
                  <el-button type="text" size="small" @click="toLogPage(scope.row.CS_ID)" icon="el-icon-document">
                    公估日志
                  </el-button>
                  <el-button type="text" size="small" @click="toCostPage(scope.row.CS_ID)" icon="el-icon-coin">
                    成本管理
                  </el-button>
                </div>
                <div>
                  <el-button type="text" size="small" @click="toContributionPage(scope.row.CS_ID)" icon="el-icon-coin">
                    案件贡献
                  </el-button>
                  <el-button type="text" size="small" @click="toIncomePage(scope.row.CS_ID)" icon="el-icon-coin">
                    案件应付
                  </el-button>
                </div>
                <div>
                  <el-button type="text" size="small" @click="toBillApplyPage(scope.row.CS_ID)" icon="el-icon-coin">
                    开票管理
                  </el-button>
                  <el-button type="text" size="small" @click="toJobPage(scope.row.CS_ID)" icon="el-icon-coin">
                    案件任务
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="total,prev,pager,next,sizes" style="float: right" background
            :current-page.sync="caseReq.pageIndex" :total="caseRes.Total" :page-size="caseReq.pageSize"
            :page-sizes="[10, 15, 20]" @size-change="
              (val) => {
                caseReq.pageSize = val
                getUnBillCases()
              }
            " @current-change="getUnBillCases()"></el-pagination>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import {
  baseURL,
  tokenName,
  empIdName
} from '@/config'
import { getUnBillCases, getUnBillCaseStat, getHosterTeam } from '@/api/personal/salemanStas'
import axios from 'axios'

export default {
  data: function () {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      activeName: 'stat',
      pageData: null,
      caseReq: {
        keyword: '',
        dlgCmpId: null,
        accidentDates: [],
        createDates: [],
        pageIndex: 1,
        pageSize: 10,
        hosterId: null,
      },
      caseRes: {
        Items: [],
        Total: 0,
      },
      hosters: [],
    }
  },
  computed: {
    ...mapGetters({
      curEmp: 'user/curEmp',
    }),
  },
  methods: {
    toCaseInfoPage(caseId) {
      this.$router.push({
        name: 'caseInfoPage',
        query: { caseId },
      })
    },
    toForm: function (formId) {
      this.$router.push({
        name: 'formInfoPage',
        query: { formId },
      })
    },
    toLogPage(caseId) {
      this.$router.push({
        name: 'caseLogPage',
        query: { caseId },
      })
    },
    toExpensePage(caseId) {
      this.$router.push({
        name: 'caseExpensePage',
        query: { caseId },
      })
    },
    toCostPage(caseId) {
      this.$router.push({
        name: 'caseCostPage',
        query: { caseId },
      })
    },
    toIncomePage(caseId) {
      this.$router.push({
        name: 'caseIncomePage',
        query: { caseId },
      })
    },
    toContributionPage(caseId) {
      this.$router.push({
        name: 'caseContributionPage',
        query: { caseId },
      })
    },
    toBillApplyPage(caseId) {
      this.$router.push({
        name: 'caseBillApplyPage',
        query: { caseId },
      })
    },
    toJobPage(caseId) {
      this.$router.push({
        name: 'caseJobPage',
        query: { caseId },
      })
    },
    getDatas() {
      this.getUnBillCases()
      this.getUnBillCaseStat()
    },
    getHosterTeam() {
      getHosterTeam().then(({ data }) => {
        this.hosters = data
      })
    },
    getUnBillCases() {
      getUnBillCases(this.caseReq).then(({ data }) => {
        this.caseRes = data
      })
    },
    getUnBillCaseStat() {
      getUnBillCaseStat(this.caseReq).then(({ data }) => {
        this.pageData = data
        this.showChart1()
      })
    },
    outputUnBillExcel() {
      var config = {
        baseURL,
        headers: {},
        responseType: 'blob',
      }
      config.headers[tokenName] = this.$store.getters['user/accessToken']
      config.headers[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
      axios
        .post(
          '/api/Personal/SalemanStas/OutputUnBillCaseExcel',
          this.caseReq,
          config
        )
        .then((response) => {
          var blob = new Blob([response.data])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '未开票报表.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch((error) => {
          console.log('response: ', error)
        })
    },
    showChart1() {
      var xAxisDatas = this.pageData.chart1.datas.map((x) => x.name)
      var seriesData1 = this.pageData.chart1.datas.map((x) => ({ id: x.cmpId, value: x.value }))
      var seriesData2 = this.pageData.chart1.datas.map((x) => ({ id: x.cmpId, value: x.count }))

      const chart1 = this.$refs.chart1
      if (chart1) {
        const myChart = this.$echarts.init(chart1)
        const option = {
          title: {
            text: this.pageData.chart1.title,
            textStyle: { fontSize: 20 },
            left: '40%',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
          },
          legend: { align: 'left', right: '10%' },
          xAxis: {
            data: xAxisDatas,
          },
          yAxis: [
            {
              type: 'value',
              name: '金额',
              axisLabel: {
                formatter: '{value} 元',
              },
            },
            {
              type: 'value',
              name: '案件数',
              position: 'right',
              axisLabel: {
                formatter: '{value} 个',
              },
              splitLine: {
                show: false,
              },
            },
          ],
          series: [
            {
              name: '待开票金额',
              type: 'bar',
              yAxisIndex: 0,
              data: seriesData1,
            },
            {
              name: '案件数',
              type: 'line',
              yAxisIndex: 1,
              data: seriesData2,
            },
          ],
        }
        myChart.setOption(option)
        myChart.on('click', ({ data }) => {
          this.caseReq.dlgCmpId = data.id
          this.activeName = 'table'
          this.getUnBillCases()
        });
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      }
      this.$on('hook:destroyed', () => {
        window.removeEventListener('resize', function () {
          myChart.resize()
        })
      })
    },
  },
  created: function () {
    var data = this.$store.getters['pagination/getRoutePage'](this.$route)
    Object.assign(this.$data, data)
    this.getHosterTeam()
    this.getDatas()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('pagination/setRoutePage', {
      route: this.$route,
      pageData: this.$data,
    })
    next()
  },
}
</script>
<style scoped>
.header {
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}

.main {
  height: 95%;
  overflow: auto;
}
</style>